package com.project.controller.serveController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.bean.GoodsBean;
import com.project.bean.ReviewBean;
import com.project.bean.ServeBean;
import com.project.service.reviewService.IReviewService;
import com.project.service.serveService.IServeService;
import com.project.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/serve")
public class ServeController {
    @Autowired
    private IServeService serveService;
    @Autowired
    private IReviewService reviewService;

    @RequestMapping("/add")
    public String add(ServeBean serve, Integer storeId,@RequestParam("face") MultipartFile mf) throws Exception {
        String fileName = UploadUtil.upload(mf,"static/html/img");
        serve.setImg(fileName);
        serveService.add(serve,storeId);
        return "ok";
    }

    @RequestMapping("/del")
    public String del(int id){
        serveService.del(id);
        return "ok";
    }

    @RequestMapping("/update")
    public String update(Integer id, String time, Integer price){
        serveService.update(id, time, price);
        return "ok";
    }

    @RequestMapping("/findById")
    public ServeBean findById(int id){
        ServeBean serve = serveService.findById(id);
        List<ReviewBean> list = reviewService.findByServeId(id);
        if(list.size() != 0){
            serve.setReviewList(list);
            double n = 0;
            for(int i=0; i<list.size(); i++) {
                n += list.get(i).getScore();
            }
            n = n / list.size();
            BigDecimal b = new BigDecimal(n);
            double f = b.setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            serve.setScore(f);
        }
        return serve;
    }

    @RequestMapping("/findAll")
    public PageInfo<ServeBean> findAll(int pageNO, int storeId){
        return serveService.findAll(pageNO, storeId);
    }

    @RequestMapping("/findByName")
    public PageInfo<ServeBean> findByName(int pageNO, String name) {
        return serveService.findByName(pageNO, name);
    }

    @RequestMapping("/delAllByStore")
    public void delAllByStore() {
        serveService.delAllByStore();
    }

    @RequestMapping("/addAllByStore")
    public void addAllByStore() {
        serveService.addAllByStore();
    }


}
